package battleship;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;

public class CacheFilter implements Filter {

    public void init(FilterConfig conf) {

    }

    public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws ServletException, IOException {

        if (req instanceof HttpServletRequest) {
            HttpServletRequest request = (HttpServletRequest) req;
            HttpServletResponse response = (HttpServletResponse) resp;

            Calendar inTwoMonths = new GregorianCalendar();
            inTwoMonths.add(Calendar.MONTH, 2);
            response.setDateHeader("Expires", inTwoMonths.getTimeInMillis());
            System.out.println("CACHE: set expiry date to 2 months");

            // rakenda järgmine filter või, kui rohkem filtreid pole
            // siis rakenda tavatoiming (Servlet, JSP või staatilise fail lugemine)
            chain.doFilter(request, response);

//            chain.doFilter(request, new ExpiresHeaderResponse(response));
        }
        chain.doFilter(req, resp);
    }

    public void destroy() {

    }
    
    public static String getResource(ServletContext c, String fileName) throws IOException {
        URL url = c.getResource(fileName);
        URLConnection connection = url.openConnection();
        connection.connect();
        long time = connection.getLastModified();
        Date d = new Date(time);
        SimpleDateFormat sdf = new SimpleDateFormat("dd-MM-yyyy-kk:mm:ss");
        String date = sdf.format(d);
        String newFileName = fileName + "?" + date;

        if (fileName.endsWith(".js")) {
            return String.format("<script type=\"text/javascript\" src=\"%s\"></script>", newFileName);
        }
        if (fileName.endsWith(".css")) {
            return String.format("<link rel=\"stylesheet\" type=\"text/css\" href=\"%s\" />", newFileName);
        }

        return "";
    }
}
